package com.example.utils.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.example.utils.listener.ReadDataListener;
import com.example.utils.listener.ReadTableListener;
import com.example.utils.vo.Test;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/utils")
public class UtilsController {

    @GetMapping("/test")
    public String test() {
        return "测试成功";
    }

    @PostMapping("/sync")
    public String sync(MultipartFile file) throws IOException {
        //第一行数据不读
        List<Object> objects = EasyExcel.read(file.getInputStream(), new ReadTableListener()).sheet().doReadSync();
        objects.forEach(object -> {
            String s = object.toString();
            int i = s.lastIndexOf("=");
            System.out.println(s.substring(i + 1, s.length() - 1));
        });
        return "OK";
    }

    @PostMapping("/async")
    public String async(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), new ReadDataListener()).sheet().doRead();
        return "OK";
    }

    @PostMapping("/write")
    public String write() throws IOException {
        List<List<String>> head = new ArrayList<>();
        EasyExcel.write("").head(head).sheet("文件模板").doWrite(Collections.emptyList());
        return "OK";
    }

    @PostMapping("/test")
    public String test(String jsonStr, MultipartFile file) {
        Test test = JSONObject.parseObject(jsonStr, Test.class);
        return "OK";
    }
}
